﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WordConfig.aspx.cs" Inherits="NX5Web.admin.BaseData.WordConfig" %>
  
<%--<link href="/Script/element-plus/index.css" rel="stylesheet" />
<script src="/Script/vue.global.min.js"></script>
<script src="/Script/jquery-3.7.1.min.js"></script>
<script src="/Script/ktlapi.js"></script>
<script src="/Script/lodash.min.js"></script> 
<script src="/Script/element-plus/zh-cn.js"></script>
<script src="/Script/element-plus/index.full.js"></script>
<script src="/Script/element-plus/index.iife.min.js"></script>
<script src="/Script/echarts-5.4.3/dist/echarts.js"></script>
<script src="/Script/sheetjs/xlsx.core.min.js"></script>
<script src="/Script/crypto-js.min.js"></script>--%>

<style>
    .scard {
        border-bottom: 1px solid rgb(119, 119, 119);
        padding: 20px;
        align-items: center;
        display: flex;
    }

    .lwords {
        border: 1px dotted #777;
        margin: 5px;
        border-radius: 5px;
        font-size: 14px;
    }

    .rdic {
        min-height: 30px;
        line-height: 30px;
        display: flex;
    }

    .ltxt {
        border-bottom: 1px dotted;
        width: 80px;
        text-align: center;
    }
    .rcontent { flex: 1; border-bottom: 1px dotted; }
    .passed { background-color: #67c23a; color: #fff; }
    .fault { background-color: #b8272c; color: #fff; }
    .el-badge__content.is-fixed { right: 33px; top: 10px; }
    .wgreen { color: #67c23a; }
    .wred { color: #b8272c; }
</style>

<div id="subApp" class="biz-container">
    <!-- 业务主体内容 -->
    <div class="left-menu-bar">
        <!-- 业务标题 -->
        <div class="left-title"><span>{{leftTitle}}</span></div>
        <el-menu @open="handleOpen" @close="handleClose" style="height: calc(100vh - 96px);overflow: scroll;">
            <el-sub-menu v-for="(lv1,lv1index) in BookList" :index="lv1.Title">
                <template #title>
                    <el-icon>
                        <location></location>
                    </el-icon>
                    <span>{{lv1.Title}}</span>
                </template>
                <el-sub-menu v-for="(lv2,lv2index) in lv1.items" :index="lv1.Title+'-'+lv2.GroupName">
                    <template #title>{{lv2.GroupName}}</template>
                    <el-menu-item @click="loadUnit(lv3)" v-for="(lv3,lv3index) in lv2.items"
                        :index="lv1.Title+'-'+lv2.GroupName+'-'+lv3.BookName">
                        <el-icon v-if="lv3.Valid" style="color:#67c23a;">
                            <bell></bell>
                        </el-icon>
                        <el-icon v-else style="color:#b8272c;">
                            <bell></bell>
                        </el-icon>
                        <span>{{lv3.BookName}}</span>
                    </el-menu-item>
                </el-sub-menu>
            </el-sub-menu>
        </el-menu>
    </div>
    <!-- 右侧业务容器 -->
    <div id="righbar" class="right-content-warp">
        <div v-show="ActiveUnit>0">
            <div>
                <div v-if="ActiveBook" @blur="changeBookTitle($event)" contenteditable v-html="ActiveBook.BookName"></div>
                <div style="border-bottom: 1px solid;">
                    <el-badge
                        class="badgeitem"
                        v-for="(item,index) in UnitList"
                        :value="item.UnConfig + '-' + item.UnAudit" 
                        :type="(item.UnConfig == 0 && item.UnAudit == 0) ? 'success' : 'danger'"
                    >
                        <el-button style="margin: 10px;" :type="item.Unit == ActiveUnit ? 'primary' : 'info'" @click="changeUnit(item)">Unit {{item.Unit}}</el-button>
                    </el-badge>
                    <el-button v-if="ActiveBook && !ActiveBook.Valid" type="danger" style="margin: 10px;" @click="deletebook()">删除本书</el-button>
                    <el-button v-if="ActiveBook && !ActiveBook.Valid" type="success" style="margin: 10px;" @click="Validbook()">正式发布</el-button>
                </div>
                <div style="display:flex; margin-top:10px;">
                    <div style="flex:3; border-right: 1px solid #777; text-align: center;">
                        <div style="font-size:12px; color:#777">未配置({{noConfigWords.length}}个)</div>
                        <div>
                            <div v-for="(item,index) in noConfigWords" class="lwords">
                                <div>{{item.Word}}</div>
                                <div>{{item.Mean}}</div>
                            </div>
                        </div>
                    </div>
                    <div style="flex:21; margin-left:5px; position:relative;">
                        <div
                            style="
                                position: fixed;
                                right: 30px;
                                bottom: 80px;
                                z-index: 9;
                                background-color: green;
                                color: #fff;
                                padding: 14px 10px;
                                border-radius: 50%;
                            "
                        >
                            <a href="javascript:document.getElementById('righbar').scrollTo(0, 0);" style="color:#fff">↑UP</a>
                        </div>

                        <div style="font-size:12px; color:#777; border-bottom: 1px solid #777; padding-bottom: 5px;">
                            共{{SentenceList.length}}个句子，{{sentenctNoPassed}}句未审核，包含{{sentenceWordCount}}个单词
                            <el-button type="primary" size="small" @click="dialogVisible = true">+</el-button>
                        </div>
                        <div style="font-size:14px;">
                            <div
                                v-for="(item,index) in SentenceList"
                                style="
                                    border-bottom: 1px solid #777;
                                    margin-bottom: 15px;
                                    width: 100%;
                                    display: flex;
                                    align-items: center;
                                    position: relative;"
                            >
                                <div style="position:absolute; top:5px; left:3px; font-size:12px; ">
                                    <div>
                                        <span v-if="item.IsAudit" class="passed">已审核</span>
                                        <span v-else class="fault">未审核</span>
                                    </div>
                                    <div>{{item.SentenceId}}</div>
                                </div>
                                <div style="width:40px; font-size:14px; text-align:center;">{{index+1}}.</div>
                                <div style="font-size:14px; flex:3;">
                                    <div class="rdic">
                                        <div class="ltxt">
                                            <div>英文</div>
                                            <div v-if="!item.IsAudit">
                                                <el-tag @click="ActiveSentence=item;showEditEn=true" type="primary" effect="dark">编辑</el-tag>
                                            </div>
                                        </div>
                                        <div style="display:flex;">
                                            <%--<div style="flex:1" class="rcontent"
                                                @blur="changeSentence($event,item,1)"
                                                :contenteditable="item.IsAudit?false:true"
                                                v-html="item.SentenceEn==null?'未生成':item.SentenceEn">
                                            </div>--%>
                                            <div
                                                v-if="item.SentenceEn != null"
                                                style="
                                                    display: flex;
                                                    flex-wrap: wrap;
                                                    border-bottom: 1px dotted;
                                                    line-height: 22px;
                                                    align-items: center;
                                                "
                                            >
                                                <div
                                                    v-if="item.Words.filter(x=>{return !x.Tag;}).length>0"
                                                    style="
                                                        padding:5px;
                                                        background-color:#ff0000;
                                                        color:#fff;
                                                        border-radius:5px;
                                                    "
                                                >异常</div>
                                                <div v-for="(wd,wdindex) in item.Words">
                                                    <div style="padding-left:5px; padding-right:5px;" :class="wd.Tag?'wgreen':'wred'">{{wd.Word}}</div>
                                                    <div style="text-align:center; font-size:12px; color:#777;border-top: 1px solid #777;">
                                                        {{wd.Index}}
                                                    </div>
                                                </div>
                                                <%--<div style="margin-left:10px;width: 45px; ">
                                                    <el-tag key="拆分" type="primary" effect="dark">拆分</el-tag>
                                                </div>--%>
                                            </div>
                                            <div v-else>未生成</div>
                                            <div style="margin-left:10px;">
                                                <template v-if="item.SentenceAudio != null">
                                                    <img @click="playvideo(item)" src="/images/audioicon.png"
                                                        style="height:35px;" />
                                                </template>
                                                <template v-else>
                                                    <el-link type="danger" @click="RenderAudio(item)">生成音频</el-link>
                                                </template>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="rdic">
                                        <div class="ltxt">中文</div>
                                        <div class="rcontent" @blur="changeSentence($event,item,2)"
                                            :contenteditable="item.IsAudit?false:true"
                                            v-html="item.SentenceCn==null?'未生成':item.SentenceCn">
                                        </div>
                                    </div>
                                    <div class="rdic">
                                        <div class="ltxt">句法</div>
                                        <div class="rcontent" @blur="changeSentence($event,item,3)"
                                            :contenteditable="item.IsAudit?false:true" v-html="item.LCType"></div>
                                    </div>
                                    <div class="rdic">
                                        <div class="ltxt">结构</div>
                                        <div class="rcontent" @blur="changeSentence($event,item,4)"
                                            :contenteditable="item.IsAudit?false:true" v-html="item.LCStruct"></div>
                                    </div>
                                    <div class="rdic">
                                        <div class="ltxt">目标</div>
                                        <div class="rcontent" @blur="changeSentence($event,item,5)"
                                            :contenteditable="item.IsAudit?false:true" v-html="item.LCTarget"></div>
                                    </div>
                                    <div class="rdic">
                                        <div class="ltxt">
                                            <div>词汇</div>
                                            <div v-if="!item.IsAudit">
                                                <el-tag @click="resetwordindex(item)" type="primary" effect="dark">重置</el-tag>
                                            </div>
                                        </div>
                                        <div class="rcontent" style="color:#777;">
                                            <div v-for="tag in item.items" :key="tag.ID" style="display:flex;">
                                                <el-tag
                                                    style="margin:3px;"
                                                    :closable="item.IsAudit?false:true"
                                                    :type="(tag.Found || (tag.Index && tag.Index.length>0)) ?'info':'danger'"
                                                    @close="closeTag(item,tag)"
                                                >
                                                    {{tag.Word}}({{tag.Mean}})
                                                </el-tag>
                                                <el-select
                                                    v-if="item.SentenceEn != null"
                                                    :disabled="item.IsAudit"
                                                    multiple
                                                    v-model="tag.Index"
                                                    style="width: 150px"
                                                    placeholder="选择序号"
                                                    @change="changewordindex(item)"
                                                >
                                                    <el-option
                                                        v-for="(ENITEM,ENINDEX) in item.SentenceEn.split(' ')"
                                                        :key="(ENINDEX+1)"
                                                        :label="(ENINDEX+1)+' - ' + ENITEM"
                                                        :value="(ENINDEX+1)">
                                                    </el-option>
                                                </el-select>
                                            </div>

                                            <div>(共{{item.items.length}}个)</div>
                                            <el-button v-show="!item.IsAudit" type="primary" size="small" @click="showUnlinkWord(item)">+</el-button>
                                        </div>
                                    </div>
                                    <div style="margin:5px;">
                                        <template v-if="!item.IsAudit">
                                            <el-button type="primary" @click="StartAI(item)">生成句子</el-button>
                                            <el-button type="danger" @click="deleteSentence(item)">删 除</el-button>
                                            <el-button type="success" @click="changeAudit(item,true)">过 审</el-button>
                                        </template>
                                        <template v-else>
                                            <el-button v-if="ActiveBook && !ActiveBook.Valid" type="danger" @click="changeAudit(item,false)">下 架</el-button>
                                        </template>
                                    </div>
                                </div>

                                <div style="flex:1; text-align:center;">
                                    <div>
                                        <span v-if="item.SentenceMedia==null">尚未生成图片</span>
                                        <img v-else style="max-height:200px;" :src="item.SentenceMedia" />
                                    </div>
                                    <div v-if="!item.IsAudit" style="display:flex;">
                                        <div style="flex:1; text-align:center;">
                                            <el-button type="primary" @click="AIDraw(item)" plain>生成图片</el-button>&nbsp;
                                        </div>
                                        <div style="flex:1; text-align:center;">
                                            <el-upload action="/ApiFilter/UploadFiles.ashx" :limit="1" :show-file-list="false" :on-success="uploadimgsuc">
                                                <template #trigger>
                                                    <el-button type="primary" @click="selectSentence(item)">上传图片</el-button>
                                                </template>
                                            </el-upload>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加句子 -->
    <el-dialog v-model="dialogVisible" title="添加" width="900">
        <div>
            <el-form :model="form" label-width="auto" style="max-width: 600px">
                <el-form-item label="句法"><el-input v-model="form.LCType" /></el-form-item>
                <el-form-item label="结构"><el-input v-model="form.LCStruct" /></el-form-item>
                <el-form-item label="目标"><el-input v-model="form.LCTarget" /></el-form-item>
                <el-form-item label="词汇">
                    <el-checkbox-group v-model="form.Words">
                        <el-checkbox v-for="(item,index) in noConfigWords" :value="item.ID" name="type">
                            {{item.Word}}({{item.Mean}})
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="AddSentence()">确 定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 添加词汇 -->
    <el-dialog v-model="dialogVisibleAddWord" title="添加词汇" width="900">
        <div>
            <el-form :model="form" label-width="auto" style="max-width: 600px">
                <el-form-item label="词汇">
                    <el-checkbox-group v-model="form.Words">
                        <el-checkbox v-for="(item,index) in noConfigWords" :value="item.ID" name="type">
                            {{item.Word}}({{item.Mean}})
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisibleAddWord = false">取 消</el-button>
                <el-button type="primary" @click="addWordToSentence()">
                    确 定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑英文句 -->
    <el-dialog v-model="showEditEn" title="编辑英文句" width="700">
        <div
            style="flex:1"
            class="rcontent"
            contenteditable
            @blur="changeSentence($event,ActiveSentence,1)"
            v-html="ActiveSentence.SentenceEn==null?'未生成':ActiveSentence.SentenceEn"
        ></div>
        <div style="font-size:12px; color:#777">修改完后自动保存</div>
    </el-dialog>

    <!-- 导入书籍 -->
    <el-dialog v-model="dialogBook" title="导入书籍" width="900">
        <div>
            <el-form label-width="auto" style="width:100%;">
                <el-form-item label="书籍">
                    <el-cascader :options="options" :props="props" v-model="importedbks" clearable style="width:100%;"></el-cascader>
                </el-form-item>
                <el-form-item label="阶段">
                    <el-select v-model="importTarget" placeholder="将选中的书导入到次阶段">
                        <el-option label="学龄前" value="1"></el-option>
                        <el-option label="小学" value="2"></el-option>
                        <el-option label="初中" value="3"></el-option>
                        <el-option label="高中" value="4"></el-option>
                        <el-option label="大学" value="5"></el-option>
                        <el-option label="成人" value="6"></el-option>
                        <el-option label="其他" value="7"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogBook = false">取 消</el-button>
                <el-button type="primary" @click="AddBookToNX5()">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</div>
<script>
    var subApp = createApp({
        el: '#subApp',
        data() {
            return {
                leftTitle: '<%= Request.QueryString["title"] %>',
                BookList: [],
                UnitList: [],
                WordList: [],
                SentenceList: [],
                ActiveUnit: 0,
                ActiveBook: null,
                ActiveSentence: null,
                form: {
                    "LCType": "",
                    "LCStruct": "",
                    "LCTarget": "",
                    "Words": []
                },
                props: { multiple: true },
                importedbks: [],
                options: [],
                dialogVisible: false,
                dialogVisibleAddWord: false,
                showEditEn: false,
                dialogBook: false,
                editSentence: null,
                importTarget: null,
            };
        },
        computed: {
            //splitSentence(item) {
            //    return item.SentenceEn.split(' ');
            //},
            noConfigWords() {
                //console.log(this.WordList);
                var temp = this.WordList.filter(x => {
                    return x.SentenceId == null
                })
                return temp;
            },
            sentenctNoPassed() {
                return this.SentenceList.filter(x => {
                    return !x.IsAudit
                }).length;
            },
            sentenceWordCount() {
                var words = 0;
                for (var i = 0; i < this.SentenceList.length; i++) {
                    words += this.SentenceList[i]["items"].length;
                }
                return words
            }
        },
        methods: {
            resetwordindex(item) {
                loaddingPlus(true);
                ktlapi({
                    "apiurl": "Word/ResetWordIndex",
                    "data": {
                        "ID": item.SentenceId
                    }
                }).then(res => {
                    //console.log(res);
                    item.WordIds = JSON.parse(res.data);
                    this.validWords();
                    loaddingPlus(false);
                });
            },
            changewordindex(item) {
                //console.log(item)
                var words = [];
                for (var i = 0; i < item.items.length; i++) {
                    words.push(
                        {
                            "ID": item.items[i]["ID"],
                            "Word": item.items[i]["Word"],
                            "Mean": item.items[i]["Mean"],
                            "Index": item.items[i]["Index"],
                            "IsExt": item.items[i]["IsExt"]
                        });
                }
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_ChangeSentenceWordIndex",
                    "data": {
                        "SentenceId": item.SentenceId,
                        "WordIds": JSON.stringify(words)
                    }
                }).then(res => {
                    loaddingPlus(false);
                });

            },
            changeBookTitle(e) {
                if (window.confirm("是否确认更名?")) {
                    loaddingPlus(true);
                    ktlapi({
                        "action": "Cus_ChangeBookTitle",
                        "data": {
                            "ID": this.ActiveBook.BookId,
                            "BookName": e.target.innerHTML
                        }
                    }).then(res => {
                        this.ActiveBook.BookName = e.target.innerHTML;
                        loaddingPlus(false);
                    });
                }
            },
            Validbook() {
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_ValidBook",
                    "data": {
                        "ID": this.ActiveBook.BookId
                    }
                }).then(res => {
                    //this.init();
                    this.ActiveBook.Valid = true;
                    loaddingPlus(false);
                });
            },
            deletebook() {
                //console.log(this.ActiveBook);
                if (window.confirm("是否确认删除本书?")) {
                    loaddingPlus(true);
                    ktlapi({
                        "action": "Cus_DeleteBook",
                        "data": {
                            "ID": this.ActiveBook.BookId
                        }
                    }).then(res => {
                        this.init();
                        loaddingPlus(false);
                    });
                }
            },
            AddBookToNX5() {
                //console.log(this.importedbks);
                if (this.importTarget == null) {
                    MsgBox.error("未选择阶段");
                    return;
                }
                if (this.importedbks.length == 0) {
                    MsgBox.error("未选择内容");
                    return;
                }
                loaddingPlus(true);

                var data = [];
                for (var i = 0; i < this.importedbks.length; i++) {
                    data.push({ "SDEBookId": this.importedbks[i][2], "TargetLv": this.importTarget })
                }
                //console.log(data);
                ktlapi({
                    "apiurl": OT.CommandAddSet,
                    "action": "Cus_ImportBookFromSDE",
                    "data": data
                }).then(res => {
                    this.dialogBook = false;
                    this.importedbks = [];
                    this.importTarget = null;
                    this.init();
                    loaddingPlus(false);
                });
            },
            sencfg(cnt) {
                var unit = this.UnitList.filter(x => {
                    return x.Unit == this.ActiveUnit
                })[0];
                unit.UnAudit += cnt;
            },
            wordcfg(cnt) {
                var unit = this.UnitList.filter(x => {
                    return x.Unit == this.ActiveUnit
                })[0];
                unit.UnConfig += cnt;
            },
            importbooks() {
                loaddingPlus(true);
                ktlapi({
                    "action": "SDE_GetOrgBooks",
                    "data": {}
                }).then(res => {
                    this.dialogBook = true;

                    this.options = pivotJson(res.data, "GroupName", ["ID", "Cus_BookId", "GroupName", "GroupDetail", "VersionName"]);
                    for (var i = 0; i < this.options.length; i++) {
                        this.options[i]["value"] = this.options[i]["GroupName"];
                        this.options[i]["label"] = this.options[i]["GroupName"];
                        this.options[i].children = pivotJson(this.options[i].items, "GroupDetail", ["ID", "Cus_BookId", "GroupName", "GroupDetail", "VersionName"]);

                        for (var j = 0; j < this.options[i].children.length; j++) {
                            this.options[i].children[j]["value"] = this.options[i].children[j]["GroupDetail"]
                            this.options[i].children[j]["label"] = this.options[i].children[j]["GroupDetail"]
                            this.options[i].children[j].children = this.options[i].children[j].items;

                            for (var k = 0; k < this.options[i].children[j].children.length; k++) {
                                this.options[i].children[j].children[k]["value"] = this.options[i].children[j].children[k]["ID"];
                                this.options[i].children[j].children[k]["label"] = this.options[i].children[j].children[k]["VersionName"]
                                if (this.options[i].children[j].children[k]["Cus_BookId"] != null) {
                                    this.options[i].children[j].children[k].disabled = true;
                                }
                            }
                        }

                    }
                    //console.log(this.options);

                    loaddingPlus(false);
                });
            },
            validWords() {
                for (var i = 0; i < this.SentenceList.length; i++) {
                    var sen = this.SentenceList[i];
                    if (sen["SentenceEn"] == null) {
                        continue;
                    } else {
                        for (var j = 0; j < this.SentenceList[i].items.length; j++) {
                            sen["items"][j]["Found"] = false;
                            //if (typeof (sen["items"][j]["Index"]) == 'undefined') {
                            //    sen["items"][j]["Index"] = [];
                            //}
                            for (var k = 0; k < this.SentenceList[i]["SentenceEn"].split(' ').length; k++) {
                                if (this.SentenceList[i]["SentenceEn"].split(' ')[k].replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "").toLowerCase() == (sen["items"][j]["Word"].toLowerCase())) {
                                    sen["items"][j]["Found"] = true;
                                    if (typeof (sen["items"][j]["Index"]) == 'undefined') {
                                        sen["items"][j]["Index"] = [];
                                    }
                                    if (sen["items"][j]["Index"].length == 0) {
                                        sen["items"][j]["Index"].push(k + 1);
                                    }
                                }
                            }
                        }
                        var SentenceWords = [];
                        //console.log(this.SentenceList[i]["WordIds"]);
                        if (this.SentenceList[i]["SentenceEn"] != null) {
                            var en = this.SentenceList[i]["SentenceEn"].split(' ');
                            for (var j = 1; j <= en.length; j++) {
                                var tag = false;
                                var word = en[j - 1];
                                for (var k = 0; k < this.SentenceList[i]["WordIds"].length; k++) {

                                    if (typeof (this.SentenceList[i]["WordIds"][k]["Index"]) == 'undefined') {
                                        this.SentenceList[i]["WordIds"][k]["Index"] = [];
                                    }

                                    if (this.SentenceList[i]["WordIds"][k]["Index"].includes(j)) {
                                        tag = true;
                                    }
                                }
                                SentenceWords.push({ "Word": word, "Index": j, "Tag": tag });
                            }
                        }
                        this.SentenceList[i]["Words"] = SentenceWords;
                        //console.log(SentenceWords);
                    }
                }
            },
            RenderAudio(item) {
                if (item.SentenceEn != null) {
                    aiAudio(item.SentenceEn, function (ret) {
                        //console.log(ret);
                        item.SentenceAudio = ret.Url;
                        loaddingPlus(true);
                        ktlapi({
                            "action": "Cus_UpdateSentence",
                            "data": {
                                SentenceId: item.SentenceId,
                                Content: item.SentenceAudio,
                                Type: 7
                            }
                        }).then(res => {
                            var row = res.data[0];
                            this.ActiveSentence.SentenceEn = row["SentenceEn"];
                            this.ActiveSentence.SentenceCn = row["SentenceCn"];
                            this.ActiveSentence.LCType = row["LCType"];
                            this.ActiveSentence.LCStruct = row["LCStruct"];
                            this.ActiveSentence.LCTarget = row["LCTarget"];
                            this.ActiveSentence.SentenceAudio = row["Audio"];
                            this.ActiveSentence.SentenceMedia = row["Media"];
                            loaddingPlus(false);
                        });
                    })
                } else {
                    MsgBox.error("没有文本");
                }
            },
            playvideo(item) {
                var audio = new Audio(item.SentenceAudio);
                audio.play();
            },
            AIDraw(item) {
                var message = [];
                if (item.SentenceEn == null) {
                    MsgBox.error("没有生成句子");
                    return;
                }
                message.push({
                    role: 'user',
                    content: "将" + item.SentenceEn + "。根据提供的句子生成一张适合学生认知水平的图片，卡通风格展示句子中的内容。不要解释。"
                        + "返回JSON格式:{\"Detail\":描述}"
                });
                //console.log(message);
                var data = '';
                loaddingPlus(true);
                aiapi(message, function (ret) {
                    //console.log("process", ret);
                    data = ret;
                }, function (ret) {
                    //console.log("done", JSON.parse(data).Detail);  
                    aiDraw(JSON.parse(data).Detail,
                        function (data) {
                            //console.log(data);
                            item.SentenceMedia = data.Url;
                            loaddingPlus(true);
                            ktlapi({
                                "action": "Cus_UpdateSentence",
                                "data": {
                                    SentenceId: item.SentenceId,
                                    Content: item.SentenceMedia,
                                    Type: 6
                                }
                            }).then(res => {
                                //console.log("res", res);
                                var row = res.data[0];
                                this.ActiveSentence.SentenceEn = row["SentenceEn"];
                                this.ActiveSentence.SentenceCn = row["SentenceCn"];
                                this.ActiveSentence.LCType = row["LCType"];
                                this.ActiveSentence.LCStruct = row["LCStruct"];
                                this.ActiveSentence.LCTarget = row["LCTarget"];
                                this.ActiveSentence.SentenceAudio = row["Audio"];
                                this.ActiveSentence.SentenceMedia = row["Media"];
                                loaddingPlus(false);
                            });
                        })

                }, function (err) {
                    if (err.isEnd) {
                        MsgBox.error(err);
                        loaddingPlus(false);
                    }
                });
            },
            selectSentence(item) {
                this.ActiveSentence = item;
            },
            uploadimgsuc(response, uploadFile) {
                //console.log(this.ActiveSentence);
                //console.log(response);
                //console.log(uploadFile); 
                var upfile = response[0]["file"];
                this.ActiveSentence["SentenceMedia"] = upfile;
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_UpdateSentence",
                    "data": {
                        SentenceId: this.ActiveSentence.SentenceId,
                        Content: upfile,
                        Type: 6
                    }
                }).then(res => {
                    var row = res.data[0];
                    this.ActiveSentence.SentenceEn = row["SentenceEn"];
                    this.ActiveSentence.SentenceCn = row["SentenceCn"];
                    this.ActiveSentence.LCType = row["LCType"];
                    this.ActiveSentence.LCStruct = row["LCStruct"];
                    this.ActiveSentence.LCTarget = row["LCTarget"];
                    this.ActiveSentence.SentenceAudio = row["Audio"];
                    this.ActiveSentence.SentenceMedia = row["Media"];
                    loaddingPlus(false);
                });

            },
            changeSentence(e, item, type) {
                //console.log(e);
                var content = e.target.innerHTML;
                var update = false;
                switch (type) {
                    case 1:
                        if (item.SentenceEn == '未生成') {
                            return;
                        }
                        if (content != item.SentenceEn) {
                            update = true;
                        }
                        break;
                    case 2:
                        if (item.SentenceCn == '未生成') {
                            return;
                        }
                        if (content != item.SentenceCn) {
                            update = true;
                        }
                        break;
                    case 3:
                        if (content != item.LCType) {
                            update = true;
                        }
                        break;
                    case 4:
                        if (content != item.LCStruct) {
                            update = true;
                        }
                        break;
                    case 5:
                        if (content != item.LCTarget) {
                            update = true;
                        }
                        break;
                    default:
                        break;
                }
                if (update) {
                    loaddingPlus(true);
                    ktlapi({
                        "action": "Cus_UpdateSentence",
                        "data": {
                            SentenceId: item.SentenceId,
                            Content: content,
                            Type: type
                        }
                    }).then(res => {
                        var row = res.data[0];
                        item.SentenceEn = row["SentenceEn"];
                        item.SentenceCn = row["SentenceCn"];
                        item.LCType = row["LCType"];
                        item.LCStruct = row["LCStruct"];
                        item.LCTarget = row["LCTarget"];
                        item.SentenceAudio = row["Audio"];
                        item.SentenceMedia = row["Media"];
                        this.validWords();
                        loaddingPlus(false);
                    });
                }
            },
            addWordToSentence() {
                //console.log(this.form.Words);
                if ((this.form.Words.length + this.editSentence.items.length) > 9) {
                    MsgBox.error("一句话中最多9个单词");
                    return;
                }
                if (this.form.Words.length == 0) {
                    MsgBox.error("未选择单词");
                    return;
                }

                for (var i = 0; i < this.form.Words.length; i++) {
                    var row = this.WordList.filter(x => {
                        return x.ID == this.form.Words[i]
                    })[0];
                    row["SentenceId"] = this.editSentence.SentenceId;
                    this.editSentence.items.push(row);
                }
                var nowWords = [];
                for (var i = 0; i < this.editSentence.items.length; i++) {
                    nowWords.push({
                        "ID": this.editSentence.items[i]["ID"],
                        "Word": this.editSentence.items[i]["Word"],
                        "Mean": this.editSentence.items[i]["Mean"],
                        "Index": [],
                        "IsExt": false
                    });
                }
                //console.log(this.editSentence.items);
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_AddWordFromSentenct",
                    "data": {
                        SentenceId: this.editSentence.SentenceId,
                        WordId: this.form.Words.toString(),
                        NowWords: JSON.stringify(nowWords)
                    }
                }).then(res => {

                    this.editSentence.SentenceEn = null;
                    this.editSentence.SentenceCn = null;
                    this.editSentence.SentenceAudio = null;
                    this.editSentence.SentenceMedia = null;
                    this.wordcfg(-1 * this.form.Words.length);
                    loaddingPlus(false);
                    this.form = {
                        "LCType": "",
                        "LCStruct": "",
                        "LCTarget": "",
                        "Words": []
                    };
                    this.dialogVisibleAddWord = false;
                });


            },
            showUnlinkWord(item) {
                this.dialogVisibleAddWord = true;
                this.editSentence = item;
            },
            StartAI(item) {
                if (item.items.length < 2) {
                    MsgBox.error("词汇量不足2-9个");
                    return;
                }

                //console.log(item);
                var that = this;

                ktlapi({
                    "action": "Cus_SentenceLoadAIContext",
                    "data": {
                        SentenceId: item.SentenceId
                    }
                }).then(res => {
                    var row = res.data[0];
                    var smsg = "";
                    var message = [];
                    if (row["AIContent"] == null) {
                        smsg += '用';
                        for (var i = 0; i < item.items.length; i++) {
                            smsg += item.items[i]["Word"] + "(" + item.items[i]["Mean"] + ")、";
                        }
                        smsg = smsg.substring(0, smsg.length - 1);

                        smsg += "组成一个句子,";


                        if (item.LCType != null && item.LCType != "") {
                            smsg += "使用" + item.LCType + "\"，\""
                        }
                        if (item.LCStruct != null && item.LCStruct != "") {
                            smsg += "参考句型:" + item.LCStruct + "\"，";
                        }
                        if (item.LCTarget != null && item.LCTarget != "") {
                            smsg += "学习目标是" + item.LCTarget + ")，"
                        }



                        smsg += "并且符合"
                            + this.ActiveBook.UseGrade
                            + "认知水平和学习水平，并且要求符合正常逻辑和伦理道德。不要解释。"
                            + "输出json格式：{\"EN\":英文句子,\"CN\":中文翻译}";
                    } else {
                        message = JSON.parse(row["AIContent"]);
                        smsg = "换一句";
                    }


                    //return;
                    message.push({
                        role: 'user',
                        content: smsg
                    });
                    //console.log(message);
                    var data = '';
                    loaddingPlus(true);
                    aiapi(message, function (ret) {
                        console.log("process", ret);
                        data = ret;
                    }, function (ret) {
                        //console.log("done", data);
                        var row = JSON.parse(data);
                        item.SentenceEn = row.EN;
                        item.SentenceCn = row.CN;
                        message.push({ role: "assistant", content: data });

                        ktlapi({
                            "action": "Cus_SentenceAIContext",
                            "data": {
                                SentenceId: item.SentenceId,
                                EN: item.SentenceEn,
                                CN: item.SentenceCn,
                                AIContent: JSON.stringify(message)
                            }
                        }).then(res => {
                            var row = res.data[0];
                            item.SentenceEn = row["SentenceEn"];
                            item.SentenceCn = row["SentenceCn"];
                            item.LCType = row["LCType"];
                            item.LCStruct = row["LCStruct"];
                            item.LCTarget = row["LCTarget"];
                            item.SentenceAudio = row["Audio"];
                            item.SentenceMedia = row["Media"];

                            that.validWords();
                            loaddingPlus(false);
                        });
                    }, function (err) {
                        if (err.isEnd) {
                            MsgBox.error(err);
                            loaddingPlus(false);
                        }
                    });
                });
            },
            closeTag(sentence, word) {
                if (sentence.items.length < 3) {
                    MsgBox.error("至少包含2个词");
                    return;
                }
                //console.log(sentence);
                //console.log(word);
                for (var i = 0; i < sentence.items.length; i++) {
                    if (sentence.items[i]["ID"] == word["ID"]) {
                        sentence.items.splice(i, 1);
                        break;
                    }
                }
                var nowWords = [];
                for (var i = 0; i < sentence.items.length; i++) {
                    nowWords.push(
                        {
                            "ID": sentence.items[i]["ID"],
                            "Word": sentence.items[i]["Word"],
                            "Mean": sentence.items[i]["Mean"],
                            "Index": sentence.items[i]["Index"],
                            "IsExt": sentence.items[i]["IsExt"]
                        });
                }
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_RemoveWordFromSentenct",
                    "data": {
                        SentenceId: sentence.SentenceId,
                        WordId: word.ID,
                        NowWords: JSON.stringify(nowWords)
                    }
                }).then(res => {
                    this.WordList.filter(x => {
                        return x.ID == word.ID
                    })[0]["SentenceId"] = null;
                    this.wordcfg(1);
                    loaddingPlus(false);
                });
            },
            deleteSentence(item) {
                if (window.confirm("是否删除该句?")) {
                    loaddingPlus(true);
                    ktlapi({
                        "action": "Cus_DeleteSentence",
                        "data": {
                            ID: item.SentenceId
                        }
                    }).then(res => {
                        this.wordcfg(item.items.length);
                        this.sencfg(-1);
                        this.loadWordAndSentence();
                        loaddingPlus(false);
                    });
                }
            },
            changeAudit(item, audit) {
                if (!audit) {
                    if (!window.confirm("是否取消审核?")) {
                        return;
                    }
                }
                if (audit == 1) {
                    if (item.SentenceEn == null) {
                        MsgBox.error("未生成英文句");
                        return;
                    }
                    if (item.SentenceCn == null) {
                        MsgBox.error("未生成中文句");
                        return;
                    }
                    //if (item.SentenceAudio == null) {
                    //    MsgBox.error("未生成音频文件");
                    //    return;
                    //}
                    //if (item.SentenceMedia == null) {
                    //    MsgBox.error("未生成媒体文件");
                    //    return;
                    //} 
                    for (var i = 0; i < item.items.length; i++) {
                        if (item.items[i]["Index"].length == 0) {
                            MsgBox.error("尚有未命中的单词");
                            return;
                        }
                    }
                }
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_UpdateSentenceAudit",
                    "data": {
                        SentenceId: item.SentenceId,
                        Audit: audit ? 1 : 0,
                    }
                }).then(res => {
                    item.IsAudit = audit;
                    this.sencfg(audit ? -1 : 1);
                    this.changewordindex(item);
                    loaddingPlus(false);
                });

            },
            AddSentence() {
                if (this.form.Words.length < 2
                    || this.form.Words.length > 9
                ) {
                    MsgBox.error("信息不全,且词汇量2-9个");
                    return;
                }

                loaddingPlus(true);
                var UseWords = [];
                for (var i = 0; i < this.form.Words.length; i++) {
                    var row = this.WordList.filter(x => {
                        return x.ID == this.form.Words[i];
                    })[0];
                    UseWords.push(
                        {
                            "ID": row["ID"],
                            "Word": row["Word"],
                            "Mean": row["Mean"],
                            "Index": [],
                            "IsExt": false
                        }
                    );
                }
                ktlapi({
                    "action": "Cus_AddTempSentence",
                    "data": {
                        "BookId": this.ActiveBook.BookId,
                        "Unit": this.ActiveUnit,
                        "LCType": this.form.LCType,
                        "LCStruct": this.form.LCStruct,
                        "LCTarget": this.form.LCTarget,
                        "WordIds": JSON.stringify(UseWords),
                        "UseGrade": this.ActiveBook["UseGrade"]
                    }
                }).then(res => {

                    this.dialogVisible = false;

                    var newSentence = res.data[0];
                    var items = [];
                    //console.log("this.form.Words",this.form.Words);
                    for (var i = 0; i < this.form.Words.length; i++) {
                        //console.log(this.form.Words[i]);
                        var row = this.WordList.filter(x => {
                            return x.ID == this.form.Words[i];
                        })[0];
                        //console.log("row", row);
                        row["SentenceId"] = newSentence["ID"];
                        items.push(row);
                    }

                    this.SentenceList.push({
                        SentenceId: newSentence["ID"],
                        SentenceEn: newSentence["SentenceEn"],
                        SentenceCn: newSentence["SentenceCn"],
                        LCType: newSentence["LCType"],
                        LCStruct: newSentence["LCStruct"],
                        LCTarget: newSentence["LCTarget"],
                        IsAudit: false,
                        SentenceAudio: newSentence["SentenceAudio"],
                        SentenceMedia: newSentence["SentenceMedia"],
                        WordIds: UseWords,
                        Words: [],
                        items: items
                    });
                    this.validWords();
                    this.wordcfg(-1 * items.length);
                    this.sencfg(1);
                    //console.log("WordList", this.WordList);

                    this.form = {
                        "LCType": "",
                        "LCStruct": "",
                        "LCTarget": "",
                        "Words": []
                    };

                    loaddingPlus(false);
                })



            },
            changeUnit(item) {
                this.ActiveUnit = item.Unit;
                this.loadWordAndSentence();
            },
            handleOpen(key, keyPath) {

            },
            handleClose(key, keyPath) {

            },
            loadUnit(item) {
                console.log("loadUnit", item);
                this.ActiveBook = item;
                this.WordList = [];
                this.SentenceList = [];
                this.UnitList = [];
                this.ActiveUnit = 0;
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_GetBookUnits",
                    "data": { "BookId": item.BookId }
                }).then(res => {
                    if (res.data == null) {
                        MsgBox.error("没有发现单词");
                    }
                    this.UnitList = res.data;
                    console.log(this.UnitList);
                    if (this.UnitList.length > 0) {
                        this.ActiveUnit = this.UnitList[0]["Unit"];
                        this.changeUnit(this.UnitList[0]);
                    }
                    loaddingPlus(false);
                })
            },
            loadWordAndSentence() {
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_WordUnitConfigBase",
                    "data": {
                        "BookId": this.ActiveBook.BookId,
                        "Unit": this.ActiveUnit
                    }
                }).then(res => {
                    this.WordList = res.data;

                    this.SentenceList = pivotJson(this.WordList.filter(x => { return x.SentenceId != null }), "SentenceId", ["SentenceId", "SentenceEn", "SentenceCn", "LCType", "LCStruct", "LCTarget", "IsAudit", "SentenceAudio", "SentenceMedia", "WordIds"], true);

                    for (var i = 0; i < this.SentenceList.length; i++) {

                        if (this.SentenceList[i]["WordIds"] == null) {
                            this.SentenceList[i]["WordIds"] = [];
                        } else {
                            this.SentenceList[i]["WordIds"] = JSON.parse(this.SentenceList[i]["WordIds"]);
                        }

                        this.SentenceList[i]["Words"] = [];
                        for (var j = 0; j < this.SentenceList[i].items.length; j++) {

                            this.SentenceList[i].items[j]["Index"] = [];

                            var row = this.SentenceList[i]["WordIds"].filter(x => {
                                return x.ID == this.SentenceList[i].items[j]["ID"]
                            });
                            for (var m = 0; m < row.length; m++) {
                                if (typeof (row[m]["Index"]) != 'undefined') {
                                    this.SentenceList[i].items[j]["Index"] = row[m]["Index"];
                                }
                            }
                        }
                    }

                    this.validWords();
                    //console.log(this.SentenceList);

                    loaddingPlus(false);
                })
            },
            init() {
                this.BookList = [];
                this.WordList = [];
                this.SentenceList = [];
                this.UnitList = [];
                this.ActiveUnit = 0;
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_GetAllBookData",
                    "data": {}
                }).then(res => {
                    loaddingPlus(false);
                    if (res.data == null) {
                        return;
                    }
                    this.BookList = pivotJson(res.data, "Title", ["BookId", "BookName", "GroupName", "Title", "UseGrade", "Valid"]);

                    for (var i = 0; i < this.BookList.length; i++) {
                        this.BookList[i]["items"] = pivotJson(this.BookList[i]["items"], "GroupName", ["BookId", "BookName", "GroupName", "Title", "UseGrade", "Valid"]);
                    }
                    //console.log(this.BookList);

                })
            }
        },
        mounted: function () {
            this.init();
        }
    });
</script>